#include "Container.h"
#include <memory>

void Container::update()
{
    if (!isVisible() || !isIniStore())
        return;

    bool needRender = isUpdataStore() ||
                      (background_color_enabled && isUpdata) ||
                      (background_image != nullptr && isUpdata);

    if (needRender)
    {
        renderSelf();
        isUpdata = false; // 确保只渲染一次
    }

    // 递归更新子容器
    for (Container *son : sons)
    {
        if (son != nullptr && son->isVisible())
        {
            son->update();
        }
    }
}
void Container::renderSelf()
{
    // 先绘制背景颜色（如果启用）
    if (background_color_enabled)
    {
        for (int i = 0; i < height * width; ++i)
        {
            store[i] = background_color;
        }
    }

    // 绘制背景图片（如果有）
    if (background_image != nullptr && background_image->get_store() != nullptr)
    {
        int *bmp_store = background_image->get_store();
        int bmp_width = background_image->get_width();
        int bmp_height = background_image->get_height();

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                int bmp_x = x % bmp_width;
                int bmp_y = y % bmp_height;
                store[y * width + x] = bmp_store[bmp_y * bmp_width + bmp_x];
            }
        }
    }
    isUpdata = false;
}

void Container::renderTo(int *target, int targetWidth, int targetHeight,
                         int offsetX, int offsetY)
{
    if (target == nullptr || !isVisible())
        return;

    //  提前计算并缓存边界
    int containerStartX = offsetX + get_pos_x();
    int containerStartY = offsetY + get_pos_y();

    //  快速判断是否完全不可见
    if (containerStartX >= targetWidth || containerStartY >= targetHeight ||
        containerStartX + width <= 0 || containerStartY + height <= 0)
        return;

    //  使用更高效的边界计算
    int startX = max(0, containerStartX);
    int startY = max(0, containerStartY);
    int endX = min(targetWidth, containerStartX + width);
    int endY = min(targetHeight, containerStartY + height);

    if (startX >= endX || startY >= endY)
        return;

    // ✅ 使用指针运算替代重复计算
    for (int y = startY; y < endY; y++)
    {
        int targetRowStart = y * targetWidth + startX;
        int sourceRowStart = (y - containerStartY) * width + (startX - containerStartX);

        for (int x = startX; x < endX; x++)
        {
            int sourceIndex = sourceRowStart + (x - startX);

            // ✅ 提前进行透明判断
            int pixelColor = store[sourceIndex];
            if (background_image != nullptr &&
                background_image->getHyalineStatus() &&
                (pixelColor & 0x00FFFFFF) == (background_image->getExcludeColor() & 0x00FFFFFF))
            {
                continue;
            }

            target[targetRowStart + (x - startX)] = pixelColor;
        }
    }

    // ✅ 递归渲染可见子容器
    for (Container *son : sons)
    {
        if (son != nullptr && son->isVisible())
        {
            son->renderTo(target, targetWidth, targetHeight, containerStartX, containerStartY);
        }
    }
}

void Container::Trigger_event()
{
    Event();
}

Container *Container::getSon(size_t index)
{
    if (index < sons.size())
    {
        return sons[index];
    }
    return nullptr;
}

bool Container::isTouch(Point &touch)
{
    int containerX = get_pos_x();
    int containerY = get_pos_y();

    return (touch.get_pos_x() >= containerX &&
            touch.get_pos_x() < containerX + width &&
            touch.get_pos_y() >= containerY &&
            touch.get_pos_y() < containerY + height &&
            Event_Type != 0);
}

Container *Container::getTouchedContainer(Point &touch)
{
    if (!isVisible() || Event_Type == 0 || !isTouch(touch))
        return nullptr;

    // 将绝对坐标转换为相对于当前容器的坐标
    Point relativeTouch(touch.get_pos_x() - get_pos_x(),
                        touch.get_pos_y() - get_pos_y());

    // 纵深搜索：从最深层子容器开始
    for (auto it = sons.rbegin(); it != sons.rend(); ++it)
    {
        Container *touched = (*it)->getTouchedContainer(relativeTouch); // 传递相对坐标
        if (touched != nullptr)
        {
            return touched;
        }
    }

    // 如果没有子容器被点击，且当前容器可点击，返回当前容器
    return this;
}

void Container::addSonAt(Container *son, size_t index)
{
    if (son != nullptr)
    {
        if (index >= sons.size())
        {
            sons.push_back(son); // 如果索引超出范围，添加到末尾
        }
        else
        {
            sons.insert(sons.begin() + index, son); // 插入到指定位置
        }
    }
}

void Container::removeSon(Container *son)
{
    if (son == nullptr)
        return;

    auto it = std::find(sons.begin(), sons.end(), son);
    if (it != sons.end())
    {
        // 先递归删除子容器的所有子容器
        for (Container *grandSon : son->sons)
        {
            son->removeSon(grandSon);
        }

        // 清空子容器的子容器列表
        son->sons.clear();

        // 从当前容器移除
        sons.erase(it);
        std::cout << "成功从父容器移除子容器" << std::endl;

        // 触发屏幕重绘
        updata_store();
        if (getParent() != nullptr)
        {
            getParent()->updata_store();
        }

        // 可选：立即删除子容器对象
        // delete son; // 注意：这需要确保没有其他地方引用这个对象
    }
}

void Container::set_pos(const int &x, const int &y)
{
    pos.set_pos(x, y);
    updata_store();
}

void Container::set_pos_x(const int &x)
{
    pos.set_pos_x(x);
    updata_store();
}

void Container::set_pos_y(const int &y)
{
    pos.set_pos_y(y);
    updata_store();
}

void Container::set_Visible(bool Status)
{
    this->Visible = Status;
}

void Container::set_Event_Type(int Status)
{
    this->Event_Type = Status;
}

int Container::set_background_color(unsigned int color)
{
    if (!isIniStore())
        return -1;

    this->background_color = color;
    this->background_color_enabled = true;

    updata_store();
    return 1;
}

int Container::set_background_image(const char *path, bool isHyaline, unsigned int Excludecolor)
{
    this->background_image = make_unique<Bmp>(path, isHyaline, Excludecolor);
    updata_store();
    return 1;
}

void Container::addSon(Container *son)
{
    if (son != nullptr)
    {
        sons.push_back(son);
    }
}

void Container::set_Event(void (*Event)())
{
    if (Event == nullptr)
        return;
    this->Event = Event;
}

void Container::align(int status, int offsetX, int offsetY)
{
    if (!parent)
        return; // 必须有父容器

    int parentWidth = parent->get_width();
    int parentHeight = parent->get_height();

    int newX = 0, newY = 0;

    switch (status)
    {
    case TOP_LEFT:
        newX = 0 + offsetX;
        newY = 0 + offsetY;
        break;
    case TOP_CENTER:
        newX = (parentWidth - width) / 2 + offsetX;
        newY = 0 + offsetY;
        break;
    case TOP_RIGHT:
        newX = parentWidth - width + offsetX;
        newY = 0 + offsetY;
        break;
    case LEFT_CENTER:
        newX = 0 + offsetX;
        newY = (parentHeight - height) / 2 + offsetY;
        break;
    case CENTER:
        newX = (parentWidth - width) / 2 + offsetX;
        newY = (parentHeight - height) / 2 + offsetY;
        break;
    case RIGHT_CENTER:
        newX = parentWidth - width + offsetX;
        newY = (parentHeight - height) / 2 + offsetY;
        break;
    case BOTTOM_LEFT:
        newX = 0 + offsetX;
        newY = parentHeight - height + offsetY;
        break;
    case BOTTOM_CENTER:
        newX = (parentWidth - width) / 2 + offsetX;
        newY = parentHeight - height + offsetY;
        break;
    case BOTTOM_RIGHT:
        newX = parentWidth - width + offsetX;
        newY = parentHeight - height + offsetY;
        break;
    }

    // 应用边界检查（使用你现有的逻辑）
    if (newX < 0)
        newX = 0;
    if (newY < 0)
        newY = 0;
    if (newX + width > parentWidth)
        newX = parentWidth - width;
    if (newY + height > parentHeight)
        newY = parentHeight - height;

    set_pos(newX, newY);
}